
package com.x52im.rbchat.logic.sns_friend.impl;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.eva.android.NewAsyncTask;
import com.eva.android.widget.WidgetUtils;
import com.eva.android.widget.alert.AlertDialog;
import com.x52im.rbchat.MyApplication;
import com.x52im.rbchat.R;
import com.x52im.rbchat.logic.chat_friend.utils.MessageHelper;
import com.x52im.rbchat.utils.ToolKits;

import java.text.MessageFormat;

/**
 * 弹出一个可填写验证请求的添加好友请求对话框（目前本wrapper类用于好友信息界面中）.
 *
 * @author JackJiang
 * @since 8.3
 */
public abstract class SendFriendReqUIWrapper {
    private Activity activity = null;
    private View layout = null;
    private EditText editSaySomething = null;
    private String nickNameOfFriend = null;

    public SendFriendReqUIWrapper(Activity activity, String nickNameOfFriend) {
        this.activity = activity;
        this.nickNameOfFriend = nickNameOfFriend;

        initViews();
    }

    private void initViews() {
        LayoutInflater inflater = activity.getLayoutInflater();
        layout = inflater.inflate(R.layout.sns_friend_request_send_form, activity.findViewById(R.id.sns_friend_request_send_form_LL));
        editSaySomething = layout.findViewById(R.id.sns_friend_request_send_form_editSaySomthing);
        editSaySomething.setHint(MessageFormat.format(activity.getString(R.string.sns_friend_request_send_form_request_saysomething_hint), nickNameOfFriend));
        final TextView editSaySomethingLengthCountView = layout.findViewById(R.id.sns_friend_request_send_form_moreDescLengthCountView);

        // 添加事件监听，实现文本输入组件已输入字数实时计算和显示
        WidgetUtils.setTextLengthCounter(editSaySomething, editSaySomethingLengthCountView);
        // 文本焦点显示在末尾
        WidgetUtils.setCursorToEnd(editSaySomething, true);
    }

    public void show() {
        new AlertDialog.Builder(activity)
                .setTitle(activity.getString(R.string.sns_friend_request_send_form_title))//MessageFormat.format($$(R.string.sns_friend_info_form_info_say_hi_title), friendInfoForInit.getNickname()))
                .setView(layout)
                .setPositiveButton(activity.getString(R.string.sns_friend_request_send_form_submit_btn_txt), (dialog, which) -> {
                    String saySomeThing = String.valueOf(editSaySomething.getText());
                    // 加好友的验证请求当然是可以为空的哦
                    sendRequest(saySomeThing);
                })
                .setNegativeButton(activity.getString(R.string.general_cancel), (dialog, which) -> dialog.dismiss())
                .show();
    }

    protected abstract void sendRequest(String saySomethingToHim);

    /**
     * 发送添加好友请求（弹出可填写验证请求的对话框形式）。
     *
     * @param activity
     * @param friendUserUid 对方的uid
     * @param friendUserNickName 对方的昵称
     * @param maxFriend 允许的最大好友数，当<=0时将忽略本参数
     */
    public static void sendAddFriendRequestWidthDialog(final Activity activity
            , final String friendUserUid
            , final String friendUserNickName
            , final int maxFriend)
    {
        new SendFriendReqUIWrapper(activity, friendUserNickName) {
            @Override
            protected void sendRequest(String saySomethingToHim) {
                sendAddFriendRequest(activity, friendUserUid, friendUserNickName, maxFriend, saySomethingToHim);
            }
        }.show();
    }

    /**
     * 发送添加好友请求的实施方法（核心实现方法），前置检查合格后发送真正的IM加好友指令。
     *
     * @param activity
     * @param friendUserUid 对方的uid
     * @param friendUserNickName 对方的昵称
     * @param maxFriend "我"被允许的最大好友数，当<=0时将忽略本参数
     * @param saySomethingToHim 加好友时的验证消息（本消息实际使用时是可能
     * 为null的哦，表示可以不输入任何想说的内容就可以加好友）
     */
    public static void sendAddFriendRequest(final Activity activity
            , final String friendUserUid
            , final String friendUserNickName
            , int maxFriend
            , final String saySomethingToHim)
    {
        if(friendUserUid == null)
            return;

        // 要加的好友是自已（这种情况应该是查找好友是查的是自已的U号或邮件地址）
        if(friendUserUid.equals(MyApplication.getInstance(activity).getIMClientManager().getLocalUserInfo().getUser_uid()))
        {
            WidgetUtils.showToastLong(activity, activity.getString(R.string.sns_friend_info_form_add_self_tip), WidgetUtils.ToastType.WARN);
            return;
        }
        else
        {
            // 检查当前要添加的好友是否已经存在于列表中（存在当然就不能重复加好友了）
            // * 注：其实最严谨的方法是服务端判断（实时根据数据结果查询），但通过网络
            // * 与服务端交互因网速原因会影响体验，所以先行在客户端做一个理论上不太严
            // * 谨的判断，先行处理掉可能的重复也是合情合理的
            if(MyApplication.getInstance(activity).getIMClientManager().getFriendsListProvider().isUserInRoster2(friendUserUid))
            {
                WidgetUtils.showToastLong(activity, MessageFormat.format(activity.getString(
                        R.string.sns_friend_info_form_has_friend_tip), friendUserNickName), WidgetUtils.ToastType.WARN);
                return;
            }

            // 最大好友数检查
            if(maxFriend > 0)
            {
                // 不能超过最大好友数
                if(MyApplication.getInstance(activity).getIMClientManager().getFriendsListProvider().size() >= maxFriend)
                {
                    new AlertDialog.Builder(activity)
                            .setTitle(MessageFormat.format(activity.getString(R.string.sns_friend_info_form_info_more_than_one_hint_title), maxFriend))
                            .setMessage(MessageFormat.format(activity.getString(R.string.sns_friend_info_form_info_more_than_one_hint_msg), maxFriend))
                            .setPositiveButton(R.string.general_ok, null)
                            .show();
                    return;
                }
            }

            // 通过了客户端初步的合法性检查，可以进入真正的添加好友业务逻辑处理：
            // 网络数据发送需要放到异步线程里（Android2.3以上版本要求网络交互不允许发生在主线程里）
            new NewAsyncTask<Object, Integer, Integer>(){
                @Override
                protected Integer doInBackground(Object... params) {
                    // 发送加好友请求
                    int code = MessageHelper.sendAddFriendRequestToServerMessage(activity, friendUserUid, saySomethingToHim);
                    return code;
                }

                @Override
                protected void onPostExecute(Integer code) {
                    if(code == 0)
                        ToolKits.showCommonTosat(activity, true, R.string.sns_friend_info_form_request_success, Toast.LENGTH_SHORT);
                    else
                        ToolKits.showCommonTosat(activity, false, R.string.sns_friend_info_form_request_fialure, Toast.LENGTH_SHORT);
                }
            }.execute();
        }
    }
}